package com.java.goodsweb.service;

import com.java.goodsweb.utils.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

/**
 * @author jl
 * @description
 * @date 2019-10-31 17:12
 */
@Service
public class GoodsHtmlService {
    @Autowired
    private TemplateEngine engine;
    @Autowired
    private GoodsService goodsService;

    /**
     * 可以使用@Async去异步执行
     */
    //@Async
    public void createHtml(Long spuId) {
        //初始化运行上下文
        Context context = new Context();
        //设置数据模型
        context.setVariables(goodsService.loadData(spuId));

        PrintWriter printWriter = null;
        try {
            //把静态文件生成到服务器本地
            File file = new File("D:\\Program Files\\nginx-1.17.4\\html\\item\\"+spuId+".html");
            printWriter = new PrintWriter(file);

            engine.process("item",context,printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    /**
     * 或者创建线程池去执行
     */
    public void asyncExecute(Long id) {
        ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(id);
            }
        });
    }

    public void deleteHtml(Long id) {
        File file = new File("D:\\Program Files\\nginx-1.17.4\\html\\item\\"+id+".html");
        file.deleteOnExit();
    }
}
